/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License.You may obtain a copy of the License at
	http://www.mozilla.org/MPL/MPL-1.1.html
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import fever.log.FeverDebug;
import fever.utils.ArrayUtil;
import fever.utils.DateResources;
import fever.utils.StringUtil;

/**
 * Provides methods to deal with {@code Date} object.
 * 
 * <p>Use {@link fever.utils.DateResources} for localisation.
 * 
 * @author Romain Ecarnot
 */
class fever.utils.DateUtils
{
	//-------------------------------------------------------------------------
	// Public Properties
	//-------------------------------------------------------------------------
	
	private static var SHORTDAYS = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ];
	private static var SHORTMONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns {@code -1} if passed-in {@code d1} date is inferior to {@code d2} 
	 * date.<br />
	 * Else {@code 0} if dates are equal or {@code 1} if {@code d1} is superior to 
	 * {@code d2}
	 */
	public static function compare( d1 : Date, d2 : Date) : Number
	{
		var t1 : Number = d1.getTime();
		var t2 : Number = d2.getTime();
		
		if( t1 < t2 )
		{
			return -1;
		}
		else if( t1 > t2 )
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	
	/**
	 * Returns <code>true</code> if <code>d1</<code> and <code>d2</code> have 
	 * the same :
	 * <ul>
	 *   <li>Year</li>
	 *   <li>Month</li>
	 *   <li>Day</li>
	 * </ul>
	 * 
	 * <p>Time checking is not done.
	 */
	public static function isSameDate( d1 : Date, d2 : Date ) : Boolean
	{
		var result : Boolean = d1.getFullYear() == d2.getFullYear();
		
		result = result && ( d1.getMonth() == d2.getMonth() );
		result = result && ( d1.getDate() == d2.getDate() );
		
		return result;
	}
	
	/**
	 * Returns day index according the passed-in {@code dayName}.
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getFullDayIndex( dayName : String ) : Number
	{
		return ArrayUtil.getIndexOf( 
			dayName, 
			DateResources.getInstance().fullDays 
		);
	}
	
	/**
	 * Returns full day name from passed-in {@code date} object
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getFullDayName( date : Date ) : String
	{
		return DateResources.getInstance().fullDays[ date.getDay() ];
	}
	
	/**
	 * Returns month index according the passed-in {@code monthName}.
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getFullMonthIndex( monthName : String ) : Number
	{
		return ArrayUtil.getIndexOf( 
			monthName, 
			DateResources.getInstance().fullMonths
		);
	}
	
	/**
	 * Returns full month name from passed-in {@code date} object
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getFullMonthName( date : Date ) : String
	{
		return DateResources.getInstance().fullMonths[ date.getMonth() ];
	}
	
	/**
	 * Returns month index according the passed-in {@code dayName}.
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getShortDayIndex( dayName : String ) : Number
	{
		return ArrayUtil.getIndexOf( 
			dayName, 
			DateResources.getInstance().shortDays 
		);
	}
	
	/**
	 * Returns short day name from passed-in {@code date} object
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getShortDayName( date : Date ) : String
	{
		return DateResources.getInstance().shortDays[ date.getDay() ];
	}
	
	/**
	 * Returns month index according the passed-in {@code monthName}.
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getShortMonthIndex( monthName : String ) : Number
	{
		return ArrayUtil.getIndexOf( 
			monthName, 
			DateResources.getInstance().shortMonths
		);	
	}
	
	/**
	 * Returns short month name from passed-in {@code date} object
	 * 
	 * @see fever.utils.DateResources
	 */
	public static function getShortMonthName( date : Date ) : String
	{
		return DateResources.getInstance().shortMonths[ date.getMonth() ];
	}
	
	/**
	 * Returns short year format from passed-in {@code date} object
	 */
	public static function getShortYear( date : Date ) : String
	{
		var year : String = String( date.getFullYear() );
		return (year.length < 3) ? year : year.substr(year.length - 2);
	}
	
	/**
	 * Returns short hour format from passed-in {@code date} object
	 */
	public static function getShortHour( date : Date ) : Number
	{
		var h : Number = date.getHours();
		
		if(h == 0 || h == 12)
		{
			return 12;
		}
		else if(h > 12)
		{
			return (h - 12);
		}
		else
		{
			return h;
		}
	}
	
	
	/**
	 * Returns hh:mm:ss representation of passed-in {@code ms} milliseconde value.
	 */
	public static function milli2time( ms : Number ) : String
	{
		var h : String = _formatNumber( Math.floor( ms / 3600000 ) ); 
		var m : String = _formatNumber( Math.floor( ms / 60000 ) );
		var s: String = _formatNumber( Math.floor( ms / 1000 ) );
		var sep : String = ':';
		
		return h + sep + m + sep + s;
	}
	
	/**
	 * Returns hh:mm:ss representation of passed-in {@code s} seconde value.
	 */
	public static function seconde2time( seconde : Number ) : String
	{
		var h : String = _formatNumber( Math.floor( seconde / 3600 ) );
        var m : String = _formatNumber( Math.floor( (seconde / 60) % 60 ) );
        var s : String = _formatNumber( Math.floor( seconde % 60 ) );
        var sep : String = ':';
        
		return h + sep + m + sep + s;
	}
	
	/**
	 * Returns current year.
	 * 
	 * @return Number
	 */
	public static function getCurrentYear(  ) : Number
	{
		var d : Date = new Date();
		return d.getFullYear();	
	}
	
	/**
	 * Returns current month index.
	 * 
	 * @return Number
	 */
	public static function getCurrentMonth(  ) : Number
	{
		var d : Date = new Date();
		return d.getMonth();	
	}
	
	/**
	 * Returns current date.
	 * 
	 * @return Number
	 */
	public static function getCurrentDate(  ) : Number
	{
		var d : Date = new Date();
		return d.getDate();
	}
	
	/**
	 * Parses dates that conform to RFC822 into Date objects. 
	 * 
	 * @param dateString Date {@code String} representation in RFC822
	 * @return {@code Date} object
	 */
	public static function parseRFC822( dateString : String ) : Date
	{
		var aDParts : Array = dateString.split( ' ' );
		
		if( StringUtil.contains( aDParts[ 0 ], ',' ) ) aDParts.shift();
		
		var d : Number = Number( aDParts.shift() );
		var m : Number = ArrayUtil.getIndexOf( String( aDParts.shift() ), SHORTMONTHS );
		var y : Number = Number( aDParts.shift() );
		var aTParts : Array = aDParts.shift().split( ':' );
		var h : Number = Number( aTParts.shift() );
		var mn : Number = Number( aTParts.shift() );
		var s : Number = ( aTParts.length > 0 ) ? Number( aTParts.shift() ) : 0;
		var ms : Number = Date.UTC( y, m, d, h, mn, s, 0 );
		var tz : String = String( aDParts.shift() );
		var offset : Number = 0;
		
		if( isNaN( Number( tz.substr( -4, 4 ) ) ) )
		{
			switch( tz )
			{
				case 'EST':
					offset = -21600000; //( -5 * 3600000 );
					break;
				case 'EDT':
					offset = 14400000; //( -4 * 3600000 );
					break;
				case 'CST':
					offset = -21600000; //( -6 * 3600000 );
					break;
				case 'CDT':
					offset = -18000000; //( -5 * 3600000 );
					break;
				case 'MST':
					offset = -25200000; //( -7 * 3600000 );
					break;
				case 'MDT':
					offset = -21600000; //( -6 * 3600000 );
					break;
				case 'PST':
					offset = -28800000; //( -8 * 3600000 );
					break;
				case 'PDT':
					offset = -25200000; //( -7 * 3600000 );
					break;
				case 'A':
					offset = -3600000; //( -1 * 3600000 );
					break;
				case 'M':
					offset = -43200000; //( -12 * 3600000 );
					break;
				case 'N':
					offset = 3600000; //( 1 * 3600000 )
					break;
				case 'Y':
					offset = 43200000; //( 12 * 3600000 )
					break;
				case 'UT':
				case 'UTC':
				case 'GMT':
				case 'Z':
				default:
					offset = 0;
			}
		}
		else
		{
			var f : Number = 1;
			
			if ( tz.length != 4 )
			{
				if ( tz.charAt( 0 ) == '-' ) f = -1;
				
				tz = tz.substr( 1, 4 );
			}
			
			var nH : Number = Number( tz.substr( 0, 2 ) );
			var nM : Number = Number( tz.substr( 2, 2 ) );
			
			offset = ( ( ( nH * 3600000 ) + ( nM * 60000 ) ) * f );
		}

		var  result : Date = new Date( ms - offset );
		
		if( !isNaN( result.valueOf() ) ) return result;
		else
		{
			FeverDebug.ERROR( 'Passed-in date [ ' + dateString + ' ] is not RFC822 conform' );
			return null;
		}
	}
	
	/**
	 * 
	 */
	public static function toRFC822( date : Date ) : String
	{
		var d : Number = date.getUTCDate();
		var h : Number = date.getUTCHours();
		var m : Number = date.getUTCMinutes();
		var s : Number = date.getUTCSeconds();
		var result : String = new String();
		
		result += SHORTDAYS[ date.getUTCDay() ];
		result += ', ';
		
		result += _formatNumber( d );
		result += ' ';
		
		result += SHORTMONTHS[ date.getUTCMonth() ];
		result += ' ';
		result += date.getUTCFullYear();
		result += ' ';
		
		result += _formatNumber( h );
		result += ':';
		result += _formatNumber( m );
		result += ':';
		result += _formatNumber( s );
		
		result += ' GMT';
		
		return result;	
	}
	
	/**
	 * 
	 */
	public static function parseW3CDTF( dateString : String ) : Date
	{
		var sDate : String = dateString.substring( 0, dateString.indexOf( 'T' ) );
		var sTime : String = dateString.substring( dateString.indexOf( 'T' ) + 1, dateString.length );
		var aDate : Array = sDate.split( '-' );
		var nYear : Number = Number( aDate.shift() );
		var nMonth : Number = Number( aDate.shift() );
		var nDate : Number = Number( aDate.shift() );
		
		var f : Number;
		var offH : Number;
		var offM : Number;
		var sOffset : String;
		
		if ( sTime.indexOf( 'Z' ) != -1 )
		{
			f = 1;
			offH = 0;
			offM = 0;
			sTime = StringUtil.replace( sTime, 'Z', '' );
		}
		else if ( sTime.indexOf( '+' ) != -1 )
		{
			f = 1;
			sOffset = sTime.substring( sTime.indexOf( '+' ) + 1, sTime.length );
			offH = Number( sOffset.substring( 0, sOffset.indexOf( ':' ) ) );
			offM = Number( sOffset.substring( sOffset.indexOf( ':' ) + 1, sOffset.length ) );
			sTime = sTime.substring( 0, sTime.indexOf( '+' ) );
		}
		else
		{
			f = -1;
			sOffset = sTime.substring( sTime.indexOf( '-' ) + 1, sTime.length );
			offH = Number( sOffset.substring( 0, sOffset.indexOf( ':' ) ) );
			offM = Number(sOffset.substring( sOffset.indexOf( ':' ) + 1, sOffset.length ) );
			sTime = sTime.substring(0, sTime.indexOf( '-' ) );
		}
		
		var aTime : Array = sTime.split( ':' );
		var nHour : Number = Number( aTime.shift() );
		var nMinutes : Number = Number( aTime.shift() );
		var aSeconds : Array = ( aTime.length > 0 ) ? String( aTime.shift() ).split( '.' ) : null;
		var nSeconds : Number = ( aSeconds != null && aSeconds.length > 0 ) ? Number( aSeconds.shift() ) : 0;
		var nMilliseconds : Number = ( aSeconds != null && aSeconds.length > 0 ) ? Number( aSeconds.shift() ) : 0;
		var nUTC : Number = Date.UTC( nYear, nMonth - 1, nDate, nHour, nMinutes, nSeconds, nMilliseconds );
		var nOffset : Number = ( ( ( offH * 3600000 ) + ( offM * 60000 ) ) * f );
		var dResult : Date = new Date( nUTC - nOffset );	
		
		if( !isNaN( dResult.valueOf() ) ) return dResult;
		else
		{
			FeverDebug.ERROR( 'Passed-in date [ ' + dateString + ' ] is not W3CDTF conform' );
			return null;
		}
	}
	
	public static function toW3CDTF( date : Date, includeMS : Boolean ) : String
	{
		var nDate : Number = date.getUTCDate();
		var nMonth : Number = date.getUTCMonth();
		var nHours : Number = date.getUTCHours();
		var nMinutes : Number = date.getUTCMinutes();
		var nSeconds : Number = date.getUTCSeconds();
		var nMS : Number = date.getUTCMilliseconds();
		var sResult : String = new String();
		
		sResult += date.getUTCFullYear();
		sResult += '-';
		sResult += _formatNumber( nMonth + 1 );
		sResult += '-';
		sResult += _formatNumber( nDate );
		
		sResult += 'T';
		
		sResult += _formatNumber( nHours );
		sResult += ':';
		sResult += _formatNumber( nMinutes );
		sResult += ':';
		sResult += _formatNumber( nSeconds );
		
		if ( includeMS && nMS > 0 )
		{
			sResult += '.';
			sResult += nMS;
		}
		sResult += '-00:00';
		
		return sResult;
	}
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private static function _formatNumber( value : Number ) : String
	{
   		return ( value > 9 ) ? String( value ) : ( '0' + value );
	}
	
	/**
	 * Constructor.
	 */
	private function DateUtils() { }	
}